import { nanoid } from "nanoid";
import { createPersistStore } from "../utils/store";
import { ChatMessage } from "./chat";
const DEFAULT_MASKTEMPLATE_STATE = {
  maskTemplates: {} as Record<string, MaskTemplate>,
};
export type MaskTemplate = {
  id: string;
  createdAt: number;
  name: string;
  context: ChatMessage[];
  variables: {
    id: string;
    var: string;
  }[];
};
export const createEmptyMaskTemplate = () =>
  ({
    id: nanoid(),
    name: "",
    createdAt: Date.now(),
    context: [],
    variables: [],
  }) as MaskTemplate;

export const useMaskTemplateStore = createPersistStore(
  { ...DEFAULT_MASKTEMPLATE_STATE },

  (set, get) => ({
    create(maskTemplate?: Partial<MaskTemplate>) {
      const maskTemplates = get().maskTemplates;
      const id = nanoid();
      maskTemplates[id] = {
        ...createEmptyMaskTemplate(),
        ...maskTemplate,
        id,
      };

      set(() => ({ maskTemplates }));
      get().markUpdate();

      return maskTemplates[id];
    },
    updateMask(id: string, updater: (maskTemplate: MaskTemplate) => void) {
      const maskTemplates = get().maskTemplates;
      const maskTemplate = maskTemplates[id];
      if (!maskTemplate) return;
      const updateMask = { ...maskTemplate };
      updater(updateMask);
      maskTemplates[id] = updateMask;
      set(() => ({ maskTemplates }));
      get().markUpdate();
    },
    delete(id: string) {
      const maskTemplates = get().maskTemplates;
      delete maskTemplates[id];
      set(() => ({ maskTemplates }));
      get().markUpdate();
    },

    get(id: string) {
      return get().maskTemplates[id];
    },
    getAll() {
      const usermaskTemplates = Object.values(get().maskTemplates).sort(
        (a, b) => b.createdAt - a.createdAt,
      );
      return usermaskTemplates;
    },
    reset() {
      set(() => ({ ...DEFAULT_MASKTEMPLATE_STATE }));
    },
  }),
  {
    name: "MaskTemplateStore", // Replace with your preferred name
    version: 2,
    migrate(persistedState) {
      // Migration logic if needed
      return persistedState as any;
    },
  },
);
